<template>
  <el-card shadow="hover" class="management-card">
    <el-form :inline="true" :model="searchForm" class="search-form">
      <el-form-item label="标题">
        <el-input v-model="searchForm.title" placeholder="请输入标题关键词" clearable />
      </el-form-item>

      <el-form-item label="状态">
        <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
          <el-option label="已发布" value="已发布" />
          <el-option label="未发布" value="未发布" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <div class="header-actions">
      <el-button class="addbutton" type="primary" size="default" @click="showAddNoticeDialog">
        <el-icon class="el-icon--left">
          <Plus />
        </el-icon>
        发布新通知
      </el-button>
    </div>

    <el-table :data="tableData" border stripe highlight-current-row style="width: 100%"
      header-row-class-name="custom-header">
      <el-table-column prop="title" label="标题" width="220" />
      <el-table-column prop="content" label="内容" width="300" show-overflow-tooltip />
      <el-table-column label="附件" width="200">
        <template #default="{ row }">
          <div v-if="row.attachments && row.attachments.length > 0">
            <div v-for="(attachment, index) in row.attachments" :key="index" class="attachment-link">
              <el-link :href="attachment.url" target="_blank">{{ attachment.name }}</el-link>
            </div>
          </div>
          <div v-else>无</div>
        </template>
      </el-table-column>
      <el-table-column prop="publisherId" label="发布人" width="70" />
      <el-table-column prop="publishTime" label="发布时间" width="160" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.status === '已发布' ? 'success' : 'warning'" effect="dark">
            {{ row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="197" align="center">
        <template #default="{ row }">
          <div class="action-buttons">
            <el-button type="primary" size="small" plain @click="editNotice(row)">
              <el-icon>
                <Edit />
              </el-icon>
            </el-button>
            <el-button type="danger" size="small" plain @click="deleteNotice(row.id)">
              <el-icon>
                <Delete />
              </el-icon>
            </el-button>
            <el-button :type="row.status === '已发布' ? 'warning' : 'success'" size="small" plain
              @click="toggleStatus(row)">
              {{ row.status === '已发布' ? '下架' : '发布' }}
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-wrapper">
      <el-pagination background layout="prev, pager, next, sizes, total" :total="total" :page-size="pageSize"
        :current-page="currentPage" @current-change="handlePageChange" @size-change="handleSizeChange" class="mt-4" />
    </div>
  </el-card>

  <!-- 通知编辑对话框 -->
  <el-dialog :title="isEditMode ? '编辑通知' : '发布新通知'" v-model="dialogVisible" width="40%" @closed="handleDialogClosed">
    <el-form :model="currentNotice" :rules="rules" ref="noticeForm" label-width="80px">
      <el-form-item label="标题" prop="title">
        <el-input v-model="currentNotice.title" placeholder="请输入通知标题" />
      </el-form-item>
      <el-form-item label="内容" prop="content">
        <el-input v-model="currentNotice.content" type="textarea" :rows="4" placeholder="请输入通知内容" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-switch v-model="currentNotice.status" active-value="已发布" inactive-value="未发布" active-text="发布"
          inactive-text="草稿" />
      </el-form-item>
      <el-form-item label="附件">
        <el-upload ref="upload" :action="uploadUrl" :headers="headers" :on-success="handleUploadSuccess"
          :on-remove="handleRemove" :file-list="currentNotice.attachments" :limit="5" :multiple="true"
          :before-upload="beforeUpload" accept=".doc,.docx,.pdf,.xls,.xlsx,.ppt,.pptx,.txt,.zip,.rar">
          <el-button type="primary">
            <el-icon>
              <Upload />
            </el-icon>
            选择文件
          </el-button>
          <template #tip>
            <div class="el-upload__tip">
              支持扩展名：.doc .docx .pdf .xls .xlsx .ppt .pptx .txt .zip .rar，单个文件不超过20MB
            </div>
          </template>
        </el-upload>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { Plus, Edit, Delete, Upload } from '@element-plus/icons-vue'
import { ref, onMounted } from 'vue'
import { ElMessage,ElMessageBox } from 'element-plus'
import { get, post2 } from '@/request/request.js'

// 数据相关
const tableData = ref([])
const total = ref(0)
const currentPage = ref(1)
let pageSize = ref(10)
const uploadUrl = 'http://localhost:5000/api/uploadNoticeFile' // 上传文件的接口地址

// 对话框相关
const dialogVisible = ref(false)
const isEditMode = ref(false)
const currentNoticeId = ref(null)
const currentNotice = ref({
  id: null,
  title: '',
  content: '',
  status: '未发布',
  publisherId: '',
  attachments: [],// 附件列表
})

// 新增上传处理方法
const handleUploadSuccess = (response, file, fileList) => {
  if (response.code === 200) {
    currentNotice.value.attachments.push({
      name: file.name,
      url: response.data,
      uid: file.uid
    })
  } else {
    ElMessage.error('上传失败')
  }
}

const handleRemove = (file, fileList) => {
  currentNotice.value.attachments = fileList
}

const beforeUpload = (file) => {
  const isLt20M = file.size / 1024 / 1024 < 20
  if (!isLt20M) {
    ElMessage.error('文件大小不能超过20MB')
    return false
  }
  return true
}

// 搜索表单数据
const searchForm = ref({
  title: '',
  status: ''
})

// 验证规则
const rules = {
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  content: [{ required: true, message: '请输入通知内容', trigger: 'blur' }],
}

// 获取数据
const fetchData = async (page = 1) => {
  try {
    const params = {
      ...searchForm.value,
      page: page,
      pageSize: pageSize.value
    }
    const response = await get('/api/notifications', params)
    tableData.value = [] // 清空旧数据
    response.data.list.forEach(r => {
      tableData.value.push({
        ...r,
        attachments: JSON.parse(r.attachments || '[]')
      })
    })
    total.value = response.data.total
  } catch (error) {
    ElMessage.error('获取通知列表失败')
    console.error('Error:', error)
  }
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  fetchData()
}

// 重置搜索
const handleReset = () => {
  searchForm.value = {
    title: '',
    status: ''
  }
  handleSearch()
}

// 新增对话框
const showAddNoticeDialog = () => {
  dialogVisible.value = true
  isEditMode.value = false
}

// 编辑通知
const editNotice = (notice) => {
  currentNotice.value = {
    ...notice,
    attachments: notice.attachments.map(att => ({
      name: att.name,
      url: att.url,
      uid: att.uid || Date.now() // 确保有唯一标识
    }))
  }
  dialogVisible.value = true
  isEditMode.value = true
}

// 删除通知
const deleteNotice = async (id) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除吗？',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    await get(`/api/deleteNotice/${id}`)
    ElMessage.success('删除成功')
    fetchData(currentPage.value)
  } catch (error) {
    ElMessage.error('删除失败')
    console.error('Error:', error)
  }
}

// 切换发布状态
const toggleStatus = async (row) => {
  try {
    const newStatus = row.status === '已发布' ? '未发布' : '已发布'
    currentNotice.value = { ...row }
    const atts = JSON.stringify(currentNotice.value.attachments.map(attach => ({
      name: (attach.name),
      url: attach.url
    })))
    const noticeData = { ...currentNotice.value ,
      attachments: atts,
      publisherId: localStorage.getItem('loginUsername'),
    }
    noticeData.status = newStatus
    await post2('/api/updateNotice', noticeData)
    row.status = newStatus
    fetchData(currentPage.value)
    ElMessage.success('状态更新成功')
  } catch (error) {
    ElMessage.error('状态更新失败')
    console.error('Error:', error)
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    const atts = JSON.stringify(currentNotice.value.attachments.map(attach => ({
      name: (attach.name),
      url: attach.url
    })))
    const noticeData = {
      ...currentNotice.value,
      attachments: atts,
      publisherId: localStorage.getItem('loginUsername'),
    }
    if (isEditMode.value) {
      noticeData.id = currentNoticeId.value
      await post2('/api/updateNotice', noticeData)
      ElMessage.success('通知信息更新成功')
    } else {
      await post2('/api/addNotice', noticeData)
      ElMessage.success('通知发布成功')
    }
    dialogVisible.value = false
    fetchData(currentPage.value)
  } catch (error) {
    ElMessage.error(isEditMode.value ? '更新失败' : '发布失败')
    console.error('Error:', error)
  }
}

// 重置表单
const handleDialogClosed = () => {
  currentNotice.value = {
    id: null,
    title: '',
    content: '',
    status: '未发布',
    publisher: '',
    attachments: [],
  }
}

// 分页处理
const handlePageChange = (page) => {
  currentPage.value = page
  fetchData(page)
}

// 每页显示数量变化
const handleSizeChange = (size) => {
  pageSize.value = size
  fetchData()
}

get

onMounted(() => {
  fetchData()
})
</script>

<style lang="scss" scoped>
.addbutton {
  margin-bottom: 5px;
  float: right;
}

.search-form {
  width: 80%;
  float: left;
  // margin-bottom: 20px;

  .el-form-item {
    margin-right: 20px;
    margin-bottom: 10px;

    &:last-child {
      margin-right: 0;
    }
  }

  .el-input,
  .el-select,
  .el-date-editor {
    width: 220px;
  }
}

.management-card {
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);

  :deep(.el-card__header) {
    border-bottom: 1px solid #ebeef5;
    background: linear-gradient(135deg, #f8f9fc, #ffffff);
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 0;

    .card-title {
      margin: 0;
      color: #303133;
      font-size: 20px;
      font-weight: 600;
      display: flex;
      align-items: center;
      gap: 8px;
    }
  }
}

.action-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.pagination-wrapper {
  margin-top: 24px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-table) {
  .el-table__cell {
    padding: 12px 0;
  }
}
</style>